
#include <klib.h>

#include <kmath.h>
#include <video.h>

int pows_of_ten[] = {1000000000, 100000000, 10000000, 1000000,
		     100000, 10000, 1000, 100, 10, 1};

int base2[] = {1073741824, 536870912, 268435456, 134217728,
               67108864,   33554432,  16777216,  8388608,
	       4194304,    2097152,   1048576,   524288,
	       262144,     131072,    65536,     32768,
	       16386,      8192,      4096,      2048,
	       1024,       512,       256,       128,
	       64,         32,        16,        8,
	       4,          2,         1};

int strlen(char *str){

  int i = 0;
  for (;; i++){
    if (str[i] == 0) return i;
  }

}

void itos(int x, char *dest, int len){

  int i = 0;

  char buf[13];         // Ten for digits, 1 for a sign, and 1 for 0 = 13 bytes

  if (len == 0) return;
  if (len == 1) {
    buf[0] = 0;
  }

  if (x == 0){
    dest[0] = '0';
    dest[1] = 0;
    return;
  }

  if (x < 0) {
    buf[0] = '-';
    i++;
    x *= -1;
  }

  int p;
  for (p = 0; p < 10; p++){
    if (x >= pows_of_ten[i]){
      int digit = x / pows_of_ten[p];
      digit %= 10;
      digit += '0';
      buf[i++] = digit;
    } else {
      buf[i++] = '0';
    }
  }

  /* Pad the rest of the buffer with 0s. */
  while ((i + 1) < 13){
    buf[i++] = 0;
  }

  /* Trim leading zeros and copy the rest into the specified dest. */
  i = 0;
  p = 0;
  if (buf[0] == '-'){
    dest[0] = '-';
    i++;
    p++;
  }
  char found = 0;
  for ( ; i < 13; i++){
    if ((p + 1) >= len){
      dest[p] = '0';      /* We have used our dest capacity */
      return;
    }
    if (buf[i] != '0'){
      found = 1;
    }
    if (found){
      dest[p++] = buf[i];
    }
  }

  while ((p + 1) < len){
    dest[p++] = 0;
  }

}

void itobs(int x, char *dest){

  int i = 0;
  for ( ; i < 31; i++){
    if (x >= base2[i]){
      dest[i + 1] = '1';
      x -= base2[i];
    } else {
      dest[i + 1] = '0';
    }
  }
  dest[0] = '0';
  dest[32] = 0;

}

int atoi(char *str, int *dest){

  int len = strlen(str);
  int i = 0;

  int val = 0;
  *dest = 0;

  for ( ; i < len; i++){
    int add, cur_ch;
    cur_ch = str[i] - '0';
    if (cur_ch < 0 || cur_ch > 9) return 0;
    add = pow(10, i);
  }

}

void memz(char *begin, int offset){

  int i = 0;
  for ( ; i < offset; i++){
    begin[i] = 0;
  }

}
